package com.ruoyi.business.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import com.ruoyi.business.domain.DefinitionInfo;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.business.domain.DefinitionDetail;
import com.ruoyi.business.service.IDefinitionDetailService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 流程定义明细Controller
 *
 * @author Gekor
 * @date 2021-07-19
 */
@Controller
@RequestMapping("/business/detail")
public class DefinitionDetailController extends BaseController {
	private String prefix = "business/detail";

	@Autowired
	private IDefinitionDetailService definitionDetailService;
	@Autowired
	private IProcessService processService;

	@RequiresPermissions("business:detail:view")
	@GetMapping("/{definitionInfoId}")
	public String detail(@PathVariable("definitionInfoId") String definitionInfoId, ModelMap modelMap) {
		modelMap.put("definitionInfoId", definitionInfoId);
		return prefix + "/detail";
	}

	/**
	 * 查询流程定义明细列表
	 */
	@RequiresPermissions("business:detail:list")
	@Log(title = "流程定义明细", businessType = BusinessType.UPDATE)
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(DefinitionDetail definitionDetail, DefinitionInfo info) {
		startPage();
		definitionDetail.setDefinitionInfo(info);
		List<DefinitionDetail> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
		return getDataTable(list);
	}

	/**
	 * 流程文件的上传和部署
	 */
	@RequiresPermissions("business:detail:deploy")
	@Log(title = "流程定义明细", businessType = BusinessType.UPDATE)
	@PostMapping("/deploy")
	@ResponseBody
	public AjaxResult deploy(MultipartFile processFile, Long definitionInfoId) {
		// 文件上传
		if (processFile != null && processFile.getSize() > 0) {
			// 判断文件类型是否是 bpmn 或 zip
			String originalFilename = processFile.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			if ("zip".equals(extName) || "bpmn".equals(extName)) {
				try {
					String pathFileName = FileUploadUtils.upload(processFile); // /profile//2021/07/19/...
					String filepath = RuoYiConfig.getProfile() + pathFileName.substring(Constants.RESOURCE_PREFIX.length() + 1);
					definitionDetailService.processDeploy(filepath, definitionInfoId);
				} catch (IOException e) {
					e.printStackTrace();
					return AjaxResult.error("流程文件部署失败");
				}
				return AjaxResult.success();
			} else {
				return AjaxResult.error("请上传zip或bpmn格式的文件");
			}
		} else {
			return AjaxResult.error("文件不能为空");
		}
	}

	/**
	 * 查看流程图或流程文件
	 */
	@Log(title = "流程定义明细", businessType = BusinessType.OTHER)
	@RequestMapping("/resource")
	public void resource(String type, String deploymentId, HttpServletResponse response) throws IOException {
		ProcessDefinition definition = processService.selectProcessDefinitonByDeployId(deploymentId);
        InputStream inputStream = null;
		if ("xml".equals(type)) {
			String resourceName = definition.getResourceName();
			inputStream = new FileInputStream(resourceName);
		} else if("png".equals(type)) {
			inputStream = processService.getImgInputStream(definition.getId(),
							Collections.EMPTY_LIST, Collections.EMPTY_LIST);
		}
        IOUtils.copy(inputStream, response.getOutputStream());
	}
}
